package com.unlcn.ils.sales.backend.service;

import com.unlcn.ils.sales.backend.bo.BonusBillBO;
import com.unlcn.ils.sales.backend.bo.UserViewBO;
import com.unlcn.ils.sales.base.mapper.SaleBonusBillMapper;
import com.unlcn.ils.sales.base.model.SaleBonusBill;
import com.unlcn.ils.sales.base.model.SaleBonusBillExample;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * Created by houjianhui on 2017/6/7.
 */
@Service
public class BonusBillServiceImpl implements BonusBillService {

    private static final Logger LOGGER = LoggerFactory.getLogger(BonusBillServiceImpl.class);

    @Autowired
    private SaleBonusBillMapper bonusBillMapper;

    @Autowired
    private UserService userService;

    @Override
    public Integer save(BonusBillBO bo) throws Exception {
        LOGGER.info("BonusBillServiceImpl.save param BonusBillBO: {}", bo);
        if (Objects.equals(bo, null) || Objects.equals(bo, "")) {
            LOGGER.info("BonusBillServiceImpl.save param BonusBillBO must not be null");
            throw new IllegalArgumentException("账单信息不能为空");
        }
        SaleBonusBill bill = new SaleBonusBill();
        BeanUtils.copyProperties(bo, bill);
        return bonusBillMapper.insertSelective(bill);
    }

    @Override
    public BonusBillBO getBonusBill(Date date) throws Exception {
        LOGGER.info("BonusBillServiceImpl.getBonusBill param date: {}", date);
        if (Objects.equals(date, null) || Objects.equals(date, "")) {
            LOGGER.info("BonusBillServiceImpl.getBonusBill param date must not be null");
            throw new IllegalArgumentException("账单日期不能为空");
        }
        UserViewBO user = userService.getCurrentUser();
        SaleBonusBillExample example = new SaleBonusBillExample();
        example.createCriteria().andUserIdEqualTo(user.getId()).andBillBeginDateGreaterThanOrEqualTo(date).andBillEndDateLessThan(date);
        List<SaleBonusBill> bills = bonusBillMapper.selectByExample(example);
        BonusBillBO bonusBill = new BonusBillBO();
        if (CollectionUtils.isNotEmpty(bills)) {
            SaleBonusBill bill = bills.get(0);
            BeanUtils.copyProperties(bill, bonusBill);
        }
        return bonusBill;
    }
}
